<template>
	<view class="add-observe">
		<view class="header">
			<rf-navbar title="创建教案" src="../../static/images/observe/add-observe-bg_top.png"
				@click="onBack"></rf-navbar>
			<image class="bg-bottom" :style="{top:navBarHeight}"
				src="../../static/images/observe/add-observe-bg_bottom.png" mode="widthFix"></image>
		</view>
		<view class="body">

			<view class="title" style="margin-top: 70rpx;">选择教案的适用年龄段</view>
			<view class="" style="display: flex; padding: 28rpx 0rpx;">
				<!-- :class="{item:selectindex==index,no_item:selectindex!=index}" @click="selectItem(index)" -->
				<view class="radiobtn" :class="{height:selectindex==0,normal:selectindex!=0}" @click="selectItem(0)">
					<span class="">托班</span>
				</view>
				<view class="radiobtn" :class="{height:selectindex==1,normal:selectindex!=1}" @click="selectItem(1)">小班
				</view>
				<view class="radiobtn" :class="{height:selectindex==2,normal:selectindex!=2}" @click="selectItem(2)">中班
				</view>
				<view class="radiobtn" :class="{height:selectindex==3,normal:selectindex!=3}" @click="selectItem(3)">大班
				</view>
			</view>

			<view style="color: #99A1AF;">
				<text style="font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.85);
				line-height: 40rpx;
				text-align: left;
				font-style: normal;">描述一下要生成的教案</text>
				<text style="margin-left: 20rpx;">( </text>
				<text>{{descriptionCount}}</text>
				<text>/</text>
				<text>100</text>
				<text> )</text>
			</view>
			<view class="observe-memoir-input mt20" style="position: relative; margin-left: 0; margin-right: 0;">
				<textarea style="white-space: pre-wrap; width: 100%;" placeholder-style="color: #99A1AF;"
					placeholder="示例一:请书写一篇剪纸艺术活动的教案。\n示例二:请书写一篇关于天气的谈话活动教案。\n示例三:请书写一篇关于引导孩子爱吃蔬菜的教案。\n(温馨提示：您可以点击键盘下方的麦克风按钮用语音输入)"
					v-model="form.description" maxlength="100" height="306rpx" count="true" confirm-type="done"
					@input="input"></textarea>
			</view>

			<rf-submit cancelText="AI生成教案" confirmText="保存" @handleUseAi="assistantShowOpen"
				@handleSave="handleSave"></rf-submit>

			<view class="title">教案生成内容</view>
			<!-- <view style="margin-left: 10rpx; display: flex;align-items: flex-start;" v-if="form.status==1">
				<view style="padding: 10rpx;">
					<image src="../../static/icons/warn.png" style="width: 28rpx; height: 28rpx;"></image>
				</view>
				<view class="">请酌情参考超小助的分析结果，根据您对孩子的了解进行相应修改。</view>
			</view> -->
			<view class="observe-analyze-measure-input mt20" style="position: relative;">
				<u--textarea v-model="form.content" placeholder="您可以在此处编辑教案" autoHeight maxlength="-1"
					:confirmType="done"></u--textarea>
				<!-- <view id="placeholderDiv" style=" position: absolute; top: 0; padding: 6px 13px; color: #a5a5a5;">
					这是一段<br>
					测试文本<br>
				</view> -->
			</view>

		</view>
		<rf-loading :loading="aiAssistant" @click="onclickHide" title="返回首页等待"></rf-loading>
		<!-- 填写观察实录提醒 -->
		<rf-toast :show="toast1" :isSus="false" :title="errMsg" @click="toast1 = false"></rf-toast>
		<!-- 创建观察成功提醒 -->
		<rf-toast :show="savePopupShow" :isSus="isSus" :title="isSus ? '教案已提交' : '创建失败'"
			@click="savePopupShow = false"></rf-toast>

		<!-- ai 分析选项 -->
		<view class="assistant-popup" v-if="assistantPopupShow">
			<u-popup :safeAreaInsetBottom="false" :show="assistantPopupShow" mode="center"
				@close="assistantPopupShow = false">
				<view style="margin-bottom: -10px;">
					<image class="assistant-icon" src="../static/images/course/courselogo.png"></image>
					<view class="title f32 bold inline">超级小助教</view>
					<view class="select-cnt">
						<view style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;">
							<u-radio-group v-model="assistant[0].value" placement="column" @change="handleAssistant">
								<u-radio style="font-size: 8px;" key="0" name="Additional.Items.WithGuidebook"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
									<view>请结合<text
											style="color: #58C866;text-decoration: underline; text-decoration-color: #58C866;"
											@click="assistantItemShow = true">{{areas1}}</text>
										<image class="icon-arrow-green" style="width: 20rpx;height: 20rpx;"></image>生成教案
									</view>
								</u-radio>

							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[1].value" placement="column">
								<u-radio key="1" :customStyle="{marginBottom: '20rpx'}" label="请写详细的教案"
									name="Content.Length.More" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
							<u-radio-group v-model="assistant[1].value" placement="column">
								<u-radio key="2" label="请写简略的教案" name="Content.Length.Less" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[2].value" placement="column">
								<u-radio key="3" label="书写活动重点和活动难点" name="Additional.activity.WithDifficulty"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-radio>
							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[3].value" placement="column">
								<u-radio key="4" label="书写活动反思" name="Additional.activity.WithReview" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>

					</view>
					<view style="height: 45px; margin: 10px 15px; display: flex; justify-content: space-between;">
						<view class="inline assistant-btn f32">
							<u-button text="取消" @click="assistantPopupShow = false"></u-button>
						</view>
						<view class="inline assistant-btn f32 save">
							<u-button text="确定" @click="handleAssistantSave"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<!-- 选择领域 -->
		<view class="assistant-popup" v-if="assistantItemShow">
			<u-popup :safeAreaInsetBottom="false" :show="assistantItemShow" mode="center"
				@close="assistantItemShow = false">
				<view style="margin-bottom: -10px;">
					<view class="title f32 bold inline">请选择</view>
					<view class="select-cnt">
						<view style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;">
							<u-radio-group v-model="selectAll" placement="column" @change="selectAssistant">
								<u-radio style="font-size: 8px;" key="0" label="相关领域" :name="true" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>

						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-checkbox-group v-model="areas" placement="column" @change="selectAssistant">
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="1" label="健康" name="健康"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="2" label="语言" name="语言"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="4" label="科学" name="科学"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="3" label="社会" name="社会"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox key="5" label="艺术" name="艺术" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
					<view style="height: 45px; margin: 10px 15px; display: flex; justify-content: space-between;">
						<view class="inline assistant-btn f32">
							<u-button text="取消" @click="assistantItemShow = false"></u-button>
						</view>
						<view class="inline assistant-btn f32 save">
							<u-button text="确定" @click="selectAssistantItem"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>

		<!-- 观察信息录入，确认弹窗 -->
		<rf-alert :show="confirmShow" @close="confirmShow=false" @confirm="confirm" title="提示"
			desc="您还没有填写生成教案信息，您是希望先保存吗？"></rf-alert>
		<!-- 按次支付观察使用 -->
		<rf-qrAlert :show="showQR" :QRUrl="QRUrl" @close="showQR=false" @confirm="handleAssistantSave"></rf-qrAlert>

		<rf-payAlert :show="android_payConfirmShow" @close="android_payConfirmShow=false" @cancel="onClicktoVip"
			@confirm="android_payConfirm" title="温馨提示" cancelText="成为VIP会员" confirmText="确定缴费">
			<view>您当前还不是超小助VIP会员，此次分析需要<text class="
				red ">{{univalence}}</text>元呦～</view>
		</rf-payAlert>

		<!-- 防止左滑返回， 当showPage值为true的时候阻挡滑动事件（滑动返回或者navback返回的滑动）-->
		<view class="" v-if="showPage">
			<page-container :show="showPage" :overlay="false" @beforeleave="beforeleave('showPage')"></page-container>
		</view>
		<!-- load -->
		<rf-load :loading="loading"></rf-load>
		<!-- 是否将观察，保存为草稿 -->
		<rf-alert :show="draftShow" @close="draftConfirm" @confirm="draftConfirm" title="温馨提示" desc="是否保存为草稿？"
			confirmText="是" cancelText="否"></rf-alert>

		<!-- 获得徽章 -->
		<rf-alertBadge :show="alertBadgeShow" :imageUrl="result.imageUrl" :name="result.name" :remark="result.remark"
			@close="alertBadgeHide"></rf-alertBadge>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState,
	} from 'vuex'; //引入mapState

	import {
		postadd,
		postgetAiById,
		putupdate,
		createPlanOrder,
	} from "@/api/coures.js"

	import {
		addAiCount,
		getAgreement,
		getServiceQRCode,
		getTeacherInfo,
	} from '@/api/user.js'

	import {
		Observable,
		from,
		interval,
		throwError,
		timer,
		BehaviorSubject
	} from 'rxjs';
	import {
		catchError,
		concatMap,
		delay,
		switchMap,
		takeWhile,
		tap,
		map,
		filter,
		take,
	} from 'rxjs/operators';

	export default {
		data() {
			return {
				showPage: true, //一开始设置为显示
				cache: true, // 是否存为草稿，在发布观察后，设置为false

				navBarHeight: this.navBarHeight,
				screenWidth: this.screenWidth,
				screenHeight: this.screenHeight,

				placeholder: "示例一:请书写一篇大班剪纸艺术活动的教案。\r\n示例二:请书写一篇通过游戏体验学习分享的社会领域活动教案。\r\n\r输入至少10个汉字。",
				// 示例三:请书写一篇关于天气的谈话活动教案。\n示例四:请书写一篇关于引导孩子爱吃蔬菜的教案。
				selectindex: 0, // 默认选中托班
				loading: false,

				form: {
					id: "",
					ageGroup: "0",
					description: "", // 分析提示
					aiAnalysisReq: "", // ai分析的条件
					content: '', // AI分析结果

					aiAnalysis: '', // ai分析的结果
					areas: [], // 其他领域

					status: "0", //  ai状态为0：未使用，1:已生成，2:生成中，
				},

				aiAssistant: false, // 智能分析中
				timer: null, // 定时器

				savePopupShow: false,
				assistantPopupShow: false,
				assistantItemShow: false,
				assistantSelect: [],
				selectAll: true, // 选择领域，全选
				areas1: "相关领域",

				assistant: [{
						value: 'Additional.Items.WithGuidebook'
					},
					{
						value: 'Content.Length.More'
					},
					{
						value: 'Additional.activity.WithDifficulty'
					},
					{
						value: 'Additional.activity.WithReview'
					},
				],
				areasSelestItems: [{
						name: "健康",
						value: "健康"
					},
					{
						name: "语言",
						value: "语言"
					},
					{
						name: "科学",
						value: "科学"
					},
					{
						name: "社会",
						value: "社会"
					},
					{
						name: "艺术",
						value: "艺术"
					},
				],
				areas: [],
				areas1s: [],

				isSus: false,

				dragging: false, // 是否正在拖拽
				mouseX: 0, // 鼠标在元素内的X坐标
				mouseY: 0, // 鼠标在元素内的Y坐标
				left: 0, // 元素左上角距离父容器左侧的距离
				top: 0, // 元素左上角距离父容器顶部的距离

				toast1: false,
				errMsg: "",

				type: "", // 状态用于标识编辑，还是新增观察

				confirmShow: false, // 确认窗口
				showVip: false, // vip 续费弹窗

				univalence: 0.0, // ai分析单次使用费用

				android_payConfirmShow: false,
				systemInfo: {}, //系统信息

				draftShow: false,

				alertBadgeShow: false, // 获取勋章提示
				result: {},

				showQR: false,
				QRUrl: "",
				descriptionCount: 0,

			}
		},
		watch: {
			assistantItemShow(newVal, oldVal) {
				this.assistantPopupShow = !newVal
				console.log(JSON.stringify(this.areas));
			},
			areas(newVal, oldVal) {
				if (newVal.length > 0) {
					this.selectAll = false;
				}
			}
		},
		computed: {
			...mapState(["userInfo"]),

			storage() {

				return (this.form.description != "" && this.form.description != null)
			}
		},
		created() {
			// 弹出徽章
			this.visibility$ = new BehaviorSubject(this.alertBadgeShow);
			this.visibility$.subscribe(isVisible => {
				this.alertBadgeShow = isVisible;
			});

			// 获取单次使用ai的费用
			this.get_univalence()
		},
		onLoad(options) {

			this.left = this.screenWidth - 80;
			this.top = this.screenHeight - 400;
			// 获取系统信息
			this.systemInfo = uni.getSystemInfoSync()

			var ageGroup_cache = uni.getStorageSync("ageGroup_cache")
			if (ageGroup_cache) {
				this.form.ageGroup = ageGroup_cache;
				this.selectindex = ageGroup_cache;
			}

			// 状态用于标识编辑，还是新增观察
			this.type = options.type
			// 如果来自于观察首页的编辑，则填充内容
			if (options.type === "update") {

				const item = JSON.parse(decodeURIComponent(options.item))
				console.log("------------更新------------" + JSON.stringify(item));

				this.form.id = item.id
				/* 教案适用班级 */
				this.form.ageGroup = item.ageGroup
				this.selectindex = item.ageGroup
				/* 教案描述 */
				this.form.description = item.description
				/* 教案内容 */
				this.form.content = item.content

				// 观察领域
				let areasArray = item.areas.split(",");
				this.form.areas = areasArray;
				this.areas = areasArray;

				if (this.areas.length > 0) {
					this.areas1 = this.formDataAreas(this.areas);
				} else {
					this.areas1 = "相关领域";
				}
				console.log("GENGXIN ----------------", this.areas);
				// ai分析
				this.form.aiAnalysis = item.aiAnalysis
				/* ai状态 */
				this.form.status = item.status

				return
			}

			// 获取缓存信息Course_draft
			var draft = uni.getStorageSync("Course_draft")
			if (draft && options.type === "create") {
				const item = JSON.parse(draft)

				this.form.id = item.id
				/* 教案适用班级 */
				this.form.ageGroup = item.ageGroup
				this.selectindex = item.ageGroup
				/* 教案描述 */
				this.form.description = item.description
				/* 教案内容 */
				this.form.content = item.content

				// ai分析
				this.form.aiAnalysis = item.aiAnalysis
				this.form.status = item.status
				return
			}
			// 创建新的
			if (options.type === "create") {
				const category_id = decodeURIComponent(options.category_id)
				console.log("创建-------------", category_id);
				if (category_id.length > 0) {
					// 临时存储
					this.areas.push(category_id);
					// url参数
					this.form.areas.push(category_id);
					// 显示
					this.areas1 = this.formDataAreas(this.areas);
				}
				console.log("------areas-------", JSON.stringify(this.areas));
				console.log("-----form--------", JSON.stringify(this.form.areas));
				console.log("------areas1-------", JSON.stringify(this.areas1));
				return
			}
		},
		onShow() {
			// 处理从第二个页面传递过来的参数

		},

		methods: {
			...mapMutations(["updateState", "updateUserInfo", "updateBadge"]),
			input(e) {
				if (e && e.detail.cursor >= 0) {
					this.descriptionCount = e.detail.cursor
				} else {
					this.descriptionCount = 0
				}

			},
			selectItem(e) {

				this.selectindex = e
				// aggGroup适用年龄段：0托班、1小班、2中班、3大班不能为空
				this.form.ageGroup = e
				uni.setStorage({
					key: 'ageGroup_cache',
					data: String(e)
				})

			},
			beforeleave() {
				//这个很重要，一定要先把弹框删除掉.
				// 如果拦截完成后，取消还停留在当前页面需要重新设置成 true
				this.showPage = false
				if (this.storage && this.cache) {
					this.draftShow = true;
				} else {
					let pages = getCurrentPages();
					if (pages.length > 1) {
						uni.navigateBack();
					}
				}
			},
			alertBadgeHide() {
				this.visibility$.next(!this.alertBadgeShow);
				// this.alertBadgeShow = false;
				// let pages = getCurrentPages();
				// if (pages.length > 1) {
				// 	uni.navigateBack();
				// }
			},
			selectAssistant(e) {
				console.log("e----------------");
				console.log(e);
				if (e == true) {
					this.areas = []
				}
				if (e.length > 0) {
					console.log(">0");
					this.selectAll = false;
				} else {
					console.log("<=0");
					this.selectAll = true;
				}
			},
			selectAssistantItem() {
				this.assistantItemShow = false;
				console.log(this.assistant[0].value);
				if (this.assistant[0].value == "Additional.Items.WithGuidebook") {
					this.areas1s = this.areas;
					if (this.areas.length > 0) {
						this.areas1 = this.formDataAreas(this.areas);
					} else {
						this.areas1 = "相关领域";
					}
				}

			},
			formDataAreas(arr) {
				var area = []
				for (var i = 0; i < arr.length; i++) {
					for (var m = 0; m < this.areasSelestItems.length; m++) {
						if (this.areasSelestItems[m].value == arr[i]) {
							area.push(this.areasSelestItems[m].name + '领域')
						}
					}
				}
				return area.toString();
			},
			onBack() {
				console.log("OnBack");
				let pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack();
				}
			},

			draftConfirm(e) {
				// 是否保存为草稿
				if (e) {
					// 临时保存观察草稿
					// 异步新增本地缓存。
					var cacheForm = this.form
					uni.setStorage({
						key: 'Course_draft',
						data: JSON.stringify(cacheForm)
					})

				} else {
					// 不保存草稿
					// 清除本地缓存
					uni.removeStorage({
						key: "Course_draft"
					})
				}

				this.draftShow = false
				// 手动执行返回
				uni.navigateBack({
					delta: 1
				})
			},

			get_univalence() {
				// 获取ai分析单次使用价格
				let _that = this;
				getAgreement(4).then(res => {
					console.log("res: " + JSON.stringify(res));
					console.log(res.data.content);
					_that.univalence = res.data.content
				}).catch(err => {

				})
			},
			android_payConfirm() {

				let _that = this;
				// 单次使用ai缴费
				if (this.systemInfo.platform === "ios") {
					this.showAlertQR()
				} else {

					from(createPlanOrder()).pipe(
						// 创建订单
						switchMap(res => {
							// 支付
							return from(_that.createPayment(res.data)).pipe(
								// 延迟两秒
								delay(2000),
								// switchMap(() => {
								// 	// 支付成功，单次AI使用数量加一
								// 	return from(addAiCount())
								// })
							);
						}),
						map(Response => {
							// 加一成功的值 输出
							console.log("Ai 使用次数加一成功后 Response: " + JSON.stringify(Response));
							return Response;
						})
					).subscribe(res => {
						// 订阅单次支付成功结果，直接使用ai助手
						this.handleAssistantSave()
					})
				}
			},
			createPayment(data) {
				let _that = this
				return new Promise((resolve, reject) => {
					uni.requestOrderPayment({
						provider: 'wxpay', //支付类型-固定值
						timeStamp: data.timeStamp.toString(), // 时间戳（单位：秒）
						nonceStr: data.nonceStr, // 随机字符串
						package: data.prepayId, // 固定值
						signType: "RSA", //固定值
						paySign: data.paySign, //签名
						success: function(res) {
							// 支付成功
							resolve(res)
							// 提示支付成功
							uni.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 2000,
								complete() {
									// 提示结束，直接去调用ai分析
								}
							})
						},
						fail: function(err) {
							reject(err)
							console.log('fail:' + JSON.stringify(err));
							// 支付失败，展示支付失败提示
							wx.showToast({
								title: '支付失败',
								icon: 'none'
							})
						}
					})
				});
			},
			onClicktoVip() {
				// 会员到期提醒，续费
				uni.navigateTo({
					url: '/pages-sub/Vip/Vip'
				})
			},
			// 不等待ai生成结果
			onclickHide() {
				// 取消订阅

				this.aiAssistant = false;
				this.cache = false // 直接返回观察信息不存草稿
				let pages = getCurrentPages()
				if (pages.length >= 1) {
					uni.navigateBack()
				}
			},
			showAlertQR() {

				this.loading = true;
				const data = {
					"memberId": "",
					"couponCode": "",
					"type": "3",
				};
				getServiceQRCode(data).then(res => {
					console.log("getServiceQRCode" + JSON.stringify(res));
					if (res.code == 200) {
						this.QRUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + res.data
						this.showQR = true;
					}
					this.loading = false;
				}).catch(err => {
					this.showQR = true;
					this.loading = false;
				})
			},
			assistantShowOpen() {

				let _that = this;

				// 会员有效后续操作
				if (!this.form.description) {
					console.log("-=--=-=--=-");
					this.errMsg = "请描述一下要生成的教案"
					this.toast1 = true
					return
				}
				if (this.form.description.length < 10) {
					uni.showToast({
						icon: "none",
						title: "输入字数不能少于10个字～",
						duration: 2000
					})
					return
				}

				// 弹出ai助手分析选项
				this.assistantPopupShow = true
			},

			// 生成的教案
			handleSave() {

				if (!this.form.description) {
					this.errMsg = "请描述一下要生成的教案"
					this.toast1 = true
					return
				}
				if (this.form.description.length < 10) {
					uni.showToast({
						icon: "none",
						title: "输入字数不能少于10个字～",
						duration: 2000
					})
					return
				}


				if (this.form.aiAnalysis == null || this.form.aiAnalysis == "") {
					// 您还没有填写观察分析与举措，您是希望先保存吗？
					this.confirmShow = true
					return
				}
				this.saveObserve()
			},

			confirm() {
				// 保存观察
				this.confirmShow = false
				this.saveObserve()
			},
			async saveObserve() {
				// 保存观察，不使用ai小助手

				// 正在提交观察
				this.loading = true

				uni.removeStorage({
					key: "Course_draft"
				})

				// this.form.aiAnalysisReq = this.assistantSelect
				this.form.aiAnalysisReq = []
				// if (this.assistantSelect.length > 0) {
				// 	// 选择了ai分析参数，提示ai生成
				// 	this.aiAssistant = true;
				// }
				// 随机一个相关领域的头像
				const randomIndex = Math.floor(Math.random() * this.areasSelestItems.length);
				this.form.areas = [this.areasSelestItems[randomIndex].value];

				console.log("res: " + JSON.stringify(this.form));
				if (this.type == "update") {
					// 更新观察
					from(putupdate(this.form)).pipe(
						tap(response => {
							if (response.code === 200) {
								// 更新成功后不需要保存草稿
								this.cache = false;
								this.loading = false;
								console.log('更新成功后不需要保存草稿');
								uni.navigateBack()
							} else if (response.statusCode === 6001) {
								// 不能使用ai分析助手，弹出请缴费
								this.android_payConfirmShow = true;
								console.log('不能使用ai分析助手，弹出请缴费');
							} else if (response.statusCode >= 500) {
								console.log('Server Error: There seems to be an issue on the server side.');
							}
						}),
						catchError(error => {

						}),
						// switchMap(data => {
						// 	return
						// })
					).subscribe(res => {
						console.log(JSON.stringify(res));
						console.log("-------------------------------");
					})

				} else {

					// 创建观察
					from(postadd(this.form)).pipe(
						tap(response => {
							if (response.code === 200) {
								// 发布过的观察信息均不需要存草稿
								this.cache = false
								this.loading = false
								if (this.assistantSelect.length <= 0) {
									this.isSus = true;
									this.savePopupShow = true;
								}
								setTimeout(() => {
									// this.aiAssistant = false;
									this.savePopupShow = false;
									if (response.data.isBadge == 1) {
										// 提示获得徽章
										this.visibility$.next(!this.alertBadgeShow);
										this.result = response.data;
										this.visibility$.pipe(
											filter(isVisible => !isVisible)
										).subscribe(() => {
											let pages = getCurrentPages();
											if (pages.length > 1) {
												uni.navigateBack();
											}
										})

									} else {
										this.cache = false
										let pages = getCurrentPages();
										if (pages.length > 1) {
											uni.navigateBack();
										}
									}
								}, 1500)
							} else if (response.statusCode === 6001) {
								// 不能使用ai分析助手，弹出请缴费
								this.android_payConfirmShow = true;
								console.log('不能使用ai分析助手，弹出请缴费');
							} else if (response.statusCode === 500) {
								this.isSus = false;
								this.savePopupShow = true;
							}
						}),

					).subscribe(res => {
						console.log("=========创建观察===========");
						console.log(JSON.stringify(res));
					})

				}
			},
			// 超级助教选择事件
			handleAssistant(even) {

				console.log(even)
				if (even == "Additional.Items.WithGuidebook") {
					this.form.areas = this.areas;
				}

			},

			getReleaseSignal(formid, resp) {
				let _that = this
				return interval(2000).pipe(
					concatMap(() => {
						if (formid) {
							// 更新观察
							console.log("------更新-----" + resp.data)
							return from(postgetAiById(resp.data))
						} else {
							console.log("------获取-----" + resp.data)
							return from(postgetAiById(resp.data))
						}
					}),
					takeWhile((result) => {
						if (result.data.status == 1) {
							// ai分析完成

							_that.aiAssistant = false;

							// 返回首页
							_that.cache = false
							uni.navigateBack()

							//停止轮询请求
							return false
						}
						return true
					})
				)
			},
			// 超级助教保存
			handleAssistantSave() {
				var _that = this
				this.assistantPopupShow = false;
				this.assistantSelect = this.assistant.map(item => {
					return item.value
				})

				// ai分析选项
				this.form.aiAnalysisReq = this.assistantSelect
				// 选择领域

				if (this.assistant[0].value == "Additional.Items.WithGuidebook") {
					console.log("=--------------", JSON.stringify(this.areas1s));
					this.form.areas = this.areas;
					if (this.form.areas.length <= 0) {
						// 生成一个随机索引
						const randomIndex = Math.floor(Math.random() * this.areasSelestItems.length);
						this.form.areas = [this.areasSelestItems[randomIndex].value];
					}
					console.log("=--------------", JSON.stringify(this.form.areas));
				}

				_that.form.status = "2" // 默认为生成中
				console.log("_that.form: " + JSON.stringify(_that.form));

				// 现获取会员信息
				// 获取一次用户信息, 会员是否有效
				// 发起请求
				from(getTeacherInfo()).pipe(
					tap(res => {
						_that.updateUserInfo(res.data)
					}),
					filter(res => {
						console.log("------this.userInfo-------", JSON.stringify(this.userInfo));
						if (this.userInfo.memberType === 0 && this.userInfo.aiUseCount <= 0) {
							// 没有会员权限
							// 弹出加入会员
							this.android_payConfirmShow = true;
							return false
						} else {
							// 有会员权限
							// 显示ai分析loading
							this.aiAssistant = true;
							// 继续信号流
							return true
						}
					}),
					switchMap(res => {
						if (_that.form.id) {
							// 更新观察的接口只返回一个观察消息的ID值
							return this.updataObseveInfo()
						} else {
							return this.createObseveInfo()
						}
					})
				).subscribe({
					next: (res) => {
						console.log('观察创建或更新结束:', res)
					},
					error: (err) => console.error('观察创建或更新失败:', err),
					complete: () => {
						// 取消loading
						// this.aiAssistant = false;
					}
				})

			},
			createObseveInfo() {
				let _that = this
				console.log("asdfasdfa----", this.form);
				// 新增操作可以产生徽章
				var source = from(postadd(_that.form))
				// source.subscribe(res => {
				// 	if (res.code === 200) {
				// 		_that.aiAssistant = false;
				// 		// 返回首页
				// 		_that.cache = false
				// 		uni.navigateBack()
				// 	}
				// 	console.log("=========创建观察===========");
				// 	console.log(JSON.stringify(res));
				// })

				source.pipe(
					filter(response => response.code === 200), // 有徽章
					switchMap((data) => {
						return _that.getReleaseSignal(_that.form.id, data)
					}),
				).subscribe(res => {
					console.log("=========获取ai返回结果===========");
					console.log(JSON.stringify(res));
				})


				source.pipe(
					filter(response => response.data.isBadge === 1), // 有徽章
					switchMap((data) => {
						// 显示徽章
						this.visibility$.next(!this.alertBadgeShow);
						this.result = data.data;
						return this.visibility$.pipe(
							filter(isVisible => !isVisible),
							switchMap(() => {
								return _that.getReleaseSignal(_that.form.id, data)
							})
						)
					}),
				).subscribe(res => {
					console.log("观察创建成功，有徽章" + res);
				})

				source.pipe(
					filter(response => response.data.isBadge === 0), // 没有徽章
					switchMap((data) => {
						return _that.getReleaseSignal(_that.form.id, data)
					}),
				).subscribe(res => {
					console.log("观察创建成功，无徽章" + res);
				})

				return source
			},
			updataObseveInfo() {
				let _that = this
				// 更新操作没有徽章
				var source = from(putupdate(this.form))
				// 更新观察的接口只返回一个观察消息的ID值
				source.pipe(
					filter(response => response.code === 200), // 更新成功
					switchMap((data) => {
						return _that.getReleaseSignal(_that.form.id, data)
					}),
				).subscribe(res => {
					console.log("更新完成，获取到ai数据" + res);
				})

				return source

			},
			handleMouseDown(event) {
				this.dragging = true;
				this.mouseX = event.changedTouches[0].clientX;
				this.mouseY = event.changedTouches[0].clientY;
			},
			handleMouseMove(event) {
				if (this.dragging) {
					console.log("event", event);
					console.log("screenWidth", this.screenWidth);
					console.log("screenHeight", this.screenHeight);
					const deltaX = event.changedTouches[0].clientX - this.mouseX;
					const deltaY = event.changedTouches[0].clientY - this.mouseY;

					var left = this.left + deltaX;
					var top = this.top + deltaY;
					if (left <= 0) {
						this.left = 0
					} else if (left >= (this.screenWidth - 70)) {
						this.left = (this.screenWidth - 70)
					} else {
						this.left = left;
					}
					if (top <= 0) {
						this.top = 0
					} else if (top >= (this.screenHeight - 70)) {
						this.top = (this.screenHeight - 70)
					} else {
						this.top = top;
					}
					this.mouseX = event.changedTouches[0].clientX;
					this.mouseY = event.changedTouches[0].clientY;
				}
			},
			handleMouseUp(event) {
				this.dragging = false;
			},
		}
	}
</script>

<style lang="scss">
	page {
		position: relative !important;
		top: 0px !important;
	}

	.add-observe {

		.header {
			position: relative;


			.bg {
				width: 100%;
				height: 64px;
				// height: 367rpx;
				position: fixed;
				z-index: 998;
				left: 0;
				top: 0;
			}

			.bg-bottom {
				position: fixed;
				left: 0;
				top: 64px;
				z-index: -1;
				width: 100vh;

				// height: 300px;
				// height: 367rpx;



			}
		}

		.body {
			position: relative;
			top: -30rpx;
			z-index: 991;
			padding: 40rpx 40rpx 190rpx 40rpx;

			.radiobtn {
				width: 120rpx;
				height: 60rpx;
				border-radius: 30rpx;

				margin-right: 28rpx;

				// 字体居中
				display: flex;
				justify-content: center;
				align-items: center;
				// 字体
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				line-height: 40rpx;
				font-style: normal;

				&.height {
					background-color: #58C866;
					color: #FFFFFF;
				}

				&.normal {
					border: 2rpx solid #58C866;
					color: #58C866;
				}
			}

			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.85);
				line-height: 40rpx;
				text-align: left;
				font-style: normal;
			}


			.observe-memoir-input,
			.observe-analyze-measure-input {
				min-height: 306rpx;
				// background: #F4F7F9;
				border-radius: 20rpx;

				font-size: 28rpx;
				line-height: 28rpx;
				letter-spacing: 3rpx;

				margin-left: -20rpx;
				margin-right: -20rpx;
			}

			.placeholder {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #99A1AF;
				line-height: 40rpx;
				text-align: justify;
				font-style: normal;
			}

			::v-deep .input-placeholder {
				// color: #b2b2b2 !important;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #99A1AF;
				line-height: 40rpx;
				text-align: left;
				font-style: normal;

			}



			/* placeholder 内容 */
			// .u-textarea-placeholder {
			// 	content: "请输入内容\n此处可以换行";
			// 	color: #999;
			// 	padding: 10px;
			// 	font-size: 14px;
			// 	line-height: 20rpx;
			// 	width: 200rpx !important;
			// }


			.u-textarea--radius {
				border: none;
				background-color: transparent;
			}

			.u-textarea__field {
				font-size: 28rpx;
				font-weight: 400;
				// color: #000000;
				color: #3A3D4B;
			}

			.create-wrap {
				display: flex;
				align-items: center;
				margin: 52rpx 16rpx 0rpx 16rpx;

				.observe-assistant {
					flex: 2;
					height: 88rpx;
					background-color: #FFA930;
					border-radius: 44rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.icon {
						width: 29px;
						height: 29px;
					}

					text {
						font-size: 16px;
						font-family: PingFangSC, PingFang SC;
						font-weight: 600;
						color: #FFFFFF;
						line-height: 22px;
					}
				}

				.save-btn {
					flex: 1;
					margin-left: 10px;

					.u-button--square {
						height: 88rpx;
						border: none;
						border-radius: 44rpx;
						background-color: #58C866;
					}

					.u-button__text {
						font-size: 16px;
						font-weight: bold;
						color: #fff;
					}
				}

			}



			.observe-details-list {
				width: 650rpx;
				height: 90rpx;
				line-height: 90rpx;
				border-bottom: 1rpx solid #EBECED;
				color: #273344;

				.icon {
					width: 32rpx;
					height: 32rpx;
					vertical-align: middle;
				}

				.text {
					margin-left: 14rpx;
				}
			}

			.observe-child {
				margin-top: 64px;
			}




			.headImg {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				flex: 1;
				height: 90rpx;
				position: relative;

				.image {
					width: 60rpx;
					height: 60rpx;
					margin: 0 5rpx;
					border-radius: 50%;
					position: relative;
				}

				.image:nth-child(5)::after {
					content: "•••";
					right: 0;
					position: absolute;
					text-align: center;
					line-height: 60rpx;
					top: 0;
					z-index: 99;
					display: inline-block;
					color: #fff;
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					background-color: rgba(0, 0, 0, 0.3);
				}

				.mask {
					position: absolute;
					top: 0;
					left: 0;
					background-color: rgba(0, 0, 0, 0.6);
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					z-index: 999;
				}
			}
		}





		.assistant-popup {
			.u-popup__content {
				width: 600rpx;
				// height: 650rpx;
				border-radius: 20rpx;
				border: 12rpx solid #F4F8F7;

				.assistant-icon {
					width: 226rpx;
					height: 322rpx;
					position: absolute;
					right: -12rpx;
					top: -194rpx;
				}

				.title {
					line-height: 22rpx;
					border-bottom: 12rpx solid rgba(88, 200, 102, .55);
					box-sizing: border-box;
					margin-top: 40rpx;
					margin-left: 28rpx;
				}

				.data-v-c4a74aee {
					font-size: 28rpx !important;
					color: #3A3D4B;
				}

				.u-checkbox__icon-wrap--circle {
					width: 32rpx !important;
					height: 32rpx !important;
				}

				.select-cnt {
					padding: 35rpx 28rpx 0;
				}

				.assistant-btn {
					width: 244rpx;
					height: 72rpx;

					.u-button--square {
						border-radius: 44rpx;
						background-color: #F2F3F7;
						color: #3A3D4B;
						border: none;
					}

					&.save {
						.u-button--square {
							background-color: #58C866;
							color: #FFF;
						}
					}
				}
			}
		}

		.popup {
			.u-popup__content {
				position: relative;
				border-radius: 24rpx 24rpx 0 0;
				overflow: hidden;
				padding-bottom: 150rpx;
			}

			.u-picker__view {
				height: 360rpx !important;
			}


			.u-toolbar__wrapper__cancel {
				padding: 0;
				position: absolute;
				left: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.u-toolbar__wrapper__confirm {
				padding: 0;
				position: absolute;
				right: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>